<template>
    <div class="article-edit">
        <el-card class="!border-none" shadow="never">
            <el-page-header :content="$route.meta.title" @back="$router.back()" />
        </el-card>
        <el-card class="mt-4 !border-none" shadow="never">
            <el-form ref="formRef" class="ls-form" label-width="140px">
                <div class="xl:flex flex-row" style="flex-wrap: wrap;">
                    <el-form-item :label="item.name" v-for="(item, index) in table_column" :key="index">
                        <!-- :rules="rules" :prop="item.column_name" -->
                        <div v-if="index == 0">
                            {{ console.log(index, "indexItem", table_column.length) }}
                        </div>
                        <div v-if="item.radio == 1">
                            <div v-if="item.column_name == 'img'" class="w-80">
                                <el-upload v-model:file-list="item.value" ref="upload" class="upload-demo" :action="action"
                                    :show-file-list="true" :headers="headers" :on-success="handleSuccess"
                                    list-type="picture">
                                    <el-button type="primary">本地上传</el-button>
                                </el-upload>
                            </div>
                            <div class="w-80" v-else>
                                <div v-if="item.type == 'data'">
                                    <el-date-picker v-model="item.value" @change="dataChange" type="date"
                                        placeholder="Pick a day" style="width: 100%;height: 40px;;" />
                                </div>
                                <div v-else-if="item.type == 'mei' || item.type == 'set'">
                                    <el-select v-model="item.value" @change="selectChange" @input="inpputChange"
                                        :data-index="index" placeholder="请选择" size="large" style="width: 100%;">
                                        <el-option v-for="(item1, index1) in item.options" :key="item1.id"
                                            :label="item1.name"
                                            :value="item.type == 'set' ? index + '-' + index1 : index + '-' + index1" />
                                    </el-select>
                                </div>
                                <div v-else>
                                    <el-input v-model="item.value" :placeholder="'请输入' + item.name" type="data"
                                        show-word-limit clearable style="width: 100%;height: 40px;;" />
                                </div>
                            </div>
                        </div>

                    </el-form-item>
                </div>
            </el-form>
        </el-card>
        <footer-btns>
            <el-button type="primary" @click="onSubmit">保存</el-button>
        </footer-btns>
    </div>
</template>

<script lang="ts" setup name="articleListsEdit">
import type { FormInstance } from 'element-plus'

import { getColumn, getDict, inforAdd, inforDetail } from '@/api/perms/role'
import { adminAll } from '@/api/perms/admin'
import { deptAll } from '@/api/org/department'

import { useDictOptions } from '@/hooks/useDictOptions'
import useMultipleTabs from '@/hooks/useMultipleTabs'

import config from '@/config'
import useAppStore from '@/stores/modules/app'
import useUserStore from '@/stores/modules/user'
// import RelationsAdd from '../components/relations-add.vue'
const userStore = useUserStore()
const appStore = useAppStore()
const action = ref(`${config.baseUrl}${config.urlPrefix}/upload/image`)
// console.log(action.value, "action")
const headers = computed(() => ({
    token: userStore.token,
    version: appStore.config.version
}))

const route = useRoute()
const router = useRouter()
const formData = reactive({
    id: '',
    title: '',
    image: '',
    cid: '',
    desc: '',
    author: '',
    content: '',
    click_virtual: 0,
    sort: 0,
    is_show: 1,
    abstract: ''
})
const table_column = ref([])
const table_admin = ref([])
const table_dept = ref([])

const dictList = ref([])


const { removeTab } = useMultipleTabs()
const formRef = shallowRef<FormInstance>()
const rules = reactive({
    dept_id: [{ required: true, message: '请选择所属部门', trigger: 'change' }],
    number: [{ required: true, message: '请输入编号', trigger: 'blur' }],
    wechat_name: [{ required: true, message: '请输入微信名称', trigger: 'blur' }],
    total_amount: [{ required: true, message: '请输入总金额', trigger: 'blur' }],
    initial_payment: [{ required: true, message: '请输入首付款', trigger: 'blur' }],
    balance_payment: [{ required: true, message: '请输入尾款', trigger: 'blur' }],
    agent_name: [{ required: true, message: '请输入中介名称', trigger: 'blur' }],
    school_name: [{ required: true, message: '请输入学校名称', trigger: 'blur' }],
    name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
    professional_name: [{ required: true, message: '请输入专业名称', trigger: 'blur' }],
    is_degree: [{ required: true, message: '请选择学位', trigger: 'change' }],
    topic_service: [{ required: true, message: '请输入题目业务', trigger: 'blur' }],
    paper_number: [{ required: true, message: '请输入字数', trigger: 'blur' }],
    duplicate_checking: [{ required: true, message: '请输入查重', trigger: 'blur' }],
    duplicate_checking_system: [{ required: true, message: '请输入查重系统', trigger: 'blur' }],
    submission_material: [{ required: true, message: '请输入交稿材料', trigger: 'blur' }],
    first_commit_time: [{ required: true, message: '请输入交稿时间', trigger: 'change' }],
    commit_time: [{ required: true, message: '请输入应交时间', trigger: 'change' }],
    commit_time11: [{ required: true, message: '请输入应交时间', trigger: 'change' }],
    // value: [{ required: true, message: '请输入应交时间', trigger: 'blur' }],

})
const getDetails = async () => {
    const data = await inforDetail({
        id: route.query.id
    })
    console.log(data)
    // Object.keys(formData).forEach((key) => {
    //     //@ts-ignore
    //     formData[key] = data[key]
    // })
}


const selectChange = (e) => {
    console.log(e, "eee")
    let index = toStr(e, 1)
    let index1 = toStr(e, 2)
    if (table_column.value[index].type == 'mei') {
        table_column.value[index].optId = table_column.value[index].options[index1].value
    }
    if (table_column.value[index].type == 'set') {
        table_column.value[index].optId = table_column.value[index].options[index1].id
    }
}
import feedback from '@/utils/feedback'
const handleSuccess = (event: any, file: any) => {
    console.log(event, file, "handleSuccess")
    if (event.show == 1) {
        feedback.msgError(`${file.name}文件上传失败`)
        // formData['fileList'] = formData['fileList'].slice(0, 1)
    } else {
        // formData.fileList[0] = {
        //     id: event.data.id,
        //     name: event.data.name,
        //     uri: event.data.uri,
        //     url: event.data.url,
        // }
        // formData.file_id = event.data.id
        // formData['fileList'] = formData['fileList'].slice(0, 1)
        // formData['file'] = formData.fileList[0]
    }
}

const dataChange = (e) => {
    console.log(e, "dataChange")
}

const inpputChange = (e) => {
    console.log(e, "eee")
}


const getlists = async () => {
    let data = await getColumn()
    table_column.value = data.column

    let data1 = await getDict()
    dictList.value = data1
    let data2 = await adminAll()
    let data3 = await deptAll()
    table_admin.value = data2
    table_dept.value = data3

    // console.log(data1, "data1", data2, data3)
    //日期
    let type_date = [
        'first_commit_time',
        'update_paper_time',
        'commit_time'
    ];
    //枚举值
    let type_mei = [
        'is_settlement',
        'is_degree',
        'hosting',
        'status',
        'dept_status',
        'charge_of_group',
        'belong_dept',
        'have_title',
        'pre_material_state',
        'is_duplicate_checking',
    ];
    //下拉选择
    let type_set = [
        'dept_id',
        'admin_id',
        'principal',
        'receiver_id',
        'after_sale_id',
    ];
    for (let i = 0; i < table_column.value.length; i++) {
        table_column.value[i].value = ''
        if (type_date.indexOf(table_column.value[i].column_name) != -1) {
            table_column.value[i].type = 'data'
        }
        if (type_mei.indexOf(table_column.value[i].column_name) != -1) {
            table_column.value[i].type = 'mei'
            let index = dictList.value.findIndex(ele => ele.type == table_column.value[i].column_name)
            if (index != -1) {
                table_column.value[i].options = dictList.value[index].options
            }
        }
        if (type_set.indexOf(table_column.value[i].column_name) != -1) {
            table_column.value[i].type = 'set'
            if (table_column.value[i].column_name == "dept_id") {
                table_column.value[i].options = data3[0].children
            } else {
                table_column.value[i].options = data2
            }
        }
    }

    // console.log(table_column.value, 'table_column')
}
const toStr = (str: string, type: number) => {
    let strs = str.split('-')
    if (type == 1) {
        return strs[0]
    } else if (type == 2) {
        return strs[1]
    }
}
const onSubmit = async () => {

    // console.log(table_column.value, "table_column")
    let arr = {};
    let name = {};

    table_column.value.forEach(element => {
        if (element.radio == 1) {
            if (element.column_name == "img") {
                let list = []

                if (element.value != "") {
                    element.value.forEach(ele => {
                        list.push(ele.response.data.id)
                    })
                    arr[element.column_name] = JSON.stringify(list)
                    name[element.column_name] = element.name
                } else {
                    arr[element.column_name] = JSON.stringify(list)
                    name[element.column_name] = element.name
                }
            } else if (element.type == "data") {
                arr[element.column_name] = element.value != "" ? Date.parse(element.value) / 1000 : ''
                name[element.column_name] = element.name
            } else if (element.type == "mei" || element.type == "set") {
                arr[element.column_name] = element.optId && element.optId != "" ? element.optId : ''
                name[element.column_name] = element.name
            } else {
                arr[element.column_name] = element.value != "" ? element.value : ''
                name[element.column_name] = element.name
                console.log(element.name, "element.name")
            }
        }

    });
    // let formEl = formRef || undefined
    // console.log(formEl,)

    // if (!formEl) return
    //  keys = []
    let keys = Object.keys(rules);
    keys.reverse();
    let fleg = ''
    keys.forEach((el, i) => {
        if (arr[el] != undefined) {
            console.log('fleg', fleg)
            if (arr[el] == '') {
                fleg = name[el]
            }
        }
        // console.log('arr', arr, el, 'el', arr[el], !arr[el])

    })
    console.log('arr', arr, 'el', name)

    console.log(keys, fleg)
    if (fleg != '') {
        feedback.msgError(`请填写` + fleg)

        return
    }
    console.log(arr, 'arr', rules);
    try {
        if (route.query.id) {
            // await noticeEdit(formData)
        } else {
            await inforAdd(arr)
        }
        removeTab()
        router.back()
    } catch (error: any) {
        for (const err in error) {
            const isInRules = Object.keys(rules).includes(err)
            isInRules && feedback.msgError(error[err][0]?.message)
        }
    }
}
getlists()
// route.query.id && getDetails()
</script>
